package com.funcablaze;

import com.funcablaze.component.Scene.Scene;
import com.funcablaze.component.control.Theme;
import com.funcablaze.func.Color;
import com.funcablaze.func.SystemThemeDetector;
import com.funcablaze.listener.Input;
import com.funcablaze.window.Frame;
import org.lwjgl.glfw.GLFW;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public final class Application {
	private static final List<Frame> windows = new ArrayList<>();
	private static boolean isGLFWInitialized = false;
	
	/**
	 * 启动应用程序
	 */
	public Application launch() {
		if (!isGLFWInitialized) {
			GLFW.glfwInit();
			GLFW.glfwDefaultWindowHints();
			GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE);
			GLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, GLFW.GLFW_TRUE);
			Runtime.getRuntime().addShutdownHook(new Thread(GLFW::glfwTerminate));
			isGLFWInitialized = true;
		}
		return this;
	}
	
	/**
	 * 添加窗口
	 * @param frame 窗口
	 */
	public static void addWindow(Frame frame) {
		windows.add(frame);
	}
	
	/**
	 * 删除窗口
	 * @param frame 窗口
	 */
	public static boolean removeWindow(Frame frame) {
		return windows.remove(frame);
	}
	
	/**
	 * 关闭软件
	 */
	public static void close() {
		for (Frame window : windows) {
			window.close();
		}
	}
	
	// 全局样式配置示例
	public static class GlobalStyle {
		public static Color backgroundColor = new Color(120, 120, 120);
	}
	
	public static void main(String[] args) {
		Application _a = new Application().launch();
		Frame frame = new Frame("Test", 800, 600);
		try {
			frame.changeScene(Scene.inflate("/Scene/MainScene.xml"));
			Theme.inflateXML("/Value/Theme.xml");
		} catch (IOException | ClassNotFoundException | ParserConfigurationException | InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException | SAXException e) {
			throw new RuntimeException(e);
		}
		Input.WindowListener windowListener = new Input.WindowListener();
		windowListener.onClose = () -> {
			frame.close();
			System.out.println("Close");
		};
		windowListener.onFocus = (focus) -> {
			if (focus) {
				frame.setTitle("Test");
			} else {
				frame.setTitle("Test - Leave");
			}
		};
		windowListener.onMinimize = (minimized) -> {
			if (minimized) {
				frame.setTitle("Test - Minimized");
			} else {
				frame.setTitle("Test");
			}
		};
		windowListener.onMaximize = (maximized) -> {
			if (maximized) {
				frame.setTitle("Test - Maximized");
			} else {
				frame.setTitle("Test");
			}
		};
		frame.setWindowListener(windowListener);
		frame.show();
		System.out.println(SystemThemeDetector.detect());
		while (frame.getScene().draw(frame.getTheme())) continue;
	}
}
